#include <stdlib.h>
#include <assert.h>
#include <pthread.h>
#include "session.h"
#include "chan.h"
#include "msg_fmt.h"

extern pkcs11fun g_function[256];
extern void function_talble_init();

void	*thread_cmd(void *argv)
{
	int	ret;
	uint16_t len;
	int	cmd;
	chan_t	*chan = (chan_t *)argv;
	buffer_t *buf;

	buf = (buffer_t *)malloc(sizeof(buffer_t));
	buf->ptr = malloc(MAX_SESSION_BUF);
	buf->size = MAX_SESSION_BUF;
	buf->len = 0;

	while(1)
	{
		ret = chan_recv2(chan, buf->ptr, 2); 
		if(ret <= 0) {
			break;
		}
		len = *(uint16_t *)buf->ptr;
		len = ntohs(len);
		ret = chan_recv2(chan, buf->ptr + 2, len); 
		if(ret <= 0) {
			break;
		}
		buf->len = len + 2;

		cmd = MSG_GET_CMD(buf->ptr);
		g_function[cmd](NULL, buf->ptr, buf->len, buf->ptr, &buf->len);
		ret = chan_send(chan, buf->ptr, buf->len);
		if(ret <= 0) {
			break;
		}
	
	}
	free(chan);
	free(buf->ptr);
	free(buf);
	return NULL;
}

int	main(int argc, char **argv)
{
	int	ret;
	chan_t	*listen_chan, *chan;
	pthread_t tid;

	function_talble_init();
	listen_chan =  chan_listen("127.0.0.1", 3344); 

	while(1)
	{
		chan = chan_accept(listen_chan);
		ret = pthread_create(&tid, NULL, thread_cmd, chan);
		assert(ret == 0);
	}

	return 0;
}
